<template>
  <view class="page-container">
    <GlobalTopBar ref="topBarRef" class="topbars" :isLeft="true" color="#fff">
      <template #title><text style="color: #fff">我的订单</text></template>
    </GlobalTopBar>
    <view class="tops">
      <SearchInput
        @search="handleSearch"
        @clear="clearFun"
        placeholder="请输入订单号"
      />
    </view>
    <!-- 内容 -->
    <view class="page_content">
      <!-- tabs -->
      <view class="tabs">
        <view
          :class="{ ac: indexs === index }"
          v-for="(item, index) in tabList"
          :key="index + 1"
          @click="indexs = index"
        >
          {{ item.text }}
        </view>
      </view>
      <!-- 列表内容 -->
      <scroll-view
        class="scroll-Y"
        scroll-y
        refresher-enabled
        :refresher-triggered="isRefreshing"
        @refresherrefresh="handleRefresh"
        @scrolltolower="handleLoadMore"
        refresher-background="#f5f5f5"
        refresher-threshold="80"
      >
        <template v-for="(item, index) in listData" :key="index + 1">
          <view
            class="libox"
            @click="store.to(`/pages/my/myorderdetails?id=${item.id}`)"
          >
            <!-- 顶部文字 -->
            <view class="libox_tops">
              <text class="t1" @click.stop="copyFun(item.tid)"
                >订单号：{{ item.tid }}</text
              >
              <text class="t2">{{
                item.is_evaluate === 1 ? '已完成' : statusData[item.user_status]
              }}</text>
            </view>
            <!-- 中间服务内容 -->
            <view class="li_center flex">
              <image
                class="cen_img"
                :src="item.service_order_goods_info.thumbnail"
                mode="aspectFill"
              />
              <view class="cen_text_box">
                <view>{{ item.service_order_goods_info.goods_title }}</view>
                <view>￥{{ item.service_order_goods_info.buy_price }}</view>
              </view>
            </view>
            <!-- 總金額 -->
            <view class="cen_je flex"
              >￥{{
                +item.service_order_initial_payment_transaction_record
                  .pay_amount +
                (+item
                  .service_order_pending_payment_balance_payment_transaction_record
                  .balance_payment_amount || 0)
              }}</view
            >
            <!-- 是否接单 -->
            <view class="jd_box flex" v-if="[2, 3].includes(item.user_status)">
              <template v-if="item.user_status === 3">
                <template v-if="!item.worker_info?.phone">
                  <view class="jd_text">未接单</view>
                  <view>平台正在努力派单，请耐心等待~</view>
                </template>

                <view class="jd_box ac" v-else>
                  <view class="flex">
                    <view class="jd_text ac">{{
                      item.service_order_dispatch_record?.status === 1
                        ? '已派单'
                        : '已接单'
                    }}</view>
                    <view>
                      {{
                        item.service_order_dispatch_record?.status === 1
                          ? '已派单，等待师傅接单'
                          : '师傅正在来的路上'
                      }}</view
                    >
                  </view>
                  <view
                    class="phone flex"
                    @click.stop="handleCall(item.worker_info?.phone)"
                  >
                    <image
                      class="head_img"
                      :src="item.worker_info?.headimg"
                      mode="scaleToFill"
                    />
                    <view
                      ><text style="margin-right: 10rpx">{{
                        item.worker_info?.worker_name
                      }}</text>
                      <text>{{ item.worker_info?.phone }}</text>
                    </view>
                    <view class="phone_img">
                      <image
                        :src="`${store.imgDomain}order_2.png`"
                        mode="scaleToFill"
                      />
                    </view>
                  </view>
                </view>
              </template>
              <template v-else-if="item.user_status === 2">
                <view class="flex" v-if="times && nminutes">
                  接单倒计时：
                  <uni-countdown
                    :show-day="false"
                    :hour="countdown(item).hours"
                    :minute="countdown(item).minutes"
                    :second="countdown(item).seconds"
                    @timeup="timeupFun(item)"
                  ></uni-countdown>
                </view>
              </template>
            </view>
            <!-- 底部时间以及功能 -->
            <view class="bottom_time_fun flex" @click.stop>
              <image
                class="time_icon"
                :src="`${store.imgDomain}order_1.png`"
                mode="scaleToFill"
              />
              <text class="time_text">{{ item.create_at }}</text>
              <view
                class="flex"
                style="margin-left: auto; width: max-content"
                @click.stop
              >
                <button
                  v-if="[3].includes(item.user_status)"
                  id="contactBtn"
                  class="flex_center"
                  open-type="contact"
                  bindcontact="onContact"
                >
                  <view class="btn">联系客服</view>
                </button>

                <view
                  class="btn ac"
                  @click.stop="qxFun(item)"
                  v-if="[2].includes(item.main_status)"
                  >取消订单</view
                >
                <picker
                  v-else-if="[3, 4].includes(item.main_status)"
                  @click.stop
                  @change="(e) => bindPickerChange(e, item)"
                  value="id"
                  :range="ReasonList"
                  range-key="cancel_service_order_reason"
                >
                  <view class="btn ac">取消订单</view>
                </picker>

                <view
                  class="btn a1"
                  @click.stop="qzfFun(item)"
                  v-if="[2].includes(item.user_status)"
                  >去支付</view
                >
                <view
                  class="btn a2"
                  v-if="
                    [4].includes(item.user_status) &&
                    item.is_balance_payment === 1 &&
                    item
                      .service_order_pending_payment_balance_payment_transaction_record
                      .status === 1
                  "
                  @click.stop="store.to(`/pages/my/jwkview?id=${item.id}`)"
                  >结尾款</view
                >
                <view
                  class="btn"
                  v-if="
                    [5].includes(item.user_status) && item.is_evaluate === 2
                  "
                  @click="
                    store.to(
                      `/pages/my/evaluate?id=${item.id}&headimg=${item.worker_info.headimg}&worker_name=${item.worker_info.worker_name}`,
                    )
                  "
                  >去评价</view
                >
                <view
                  class="btn"
                  v-else-if="
                    [5].includes(item.user_status) && item.is_evaluate === 1
                  "
                  @click="store.to(`/pages/my/myorderdetails?id=${item.id}`)"
                  >已评价</view
                >
                <view
                  v-if="
                    [5].includes(item.user_status) && item.is_complaint === 2
                  "
                  class="btn"
                  @click="
                    store.to(
                      `/pages/my/launchcomplaint?id=${item.id}&price=${item.service_order_initial_payment_transaction_record.pay_amount}`,
                    )
                  "
                  >发起投诉</view
                >
                <view
                  class="btn"
                  v-else-if="
                    [5].includes(item.user_status) && item.is_complaint === 1
                  "
                  @click="store.to(`/pages/my/myorderdetails?id=${item.id}`)"
                  >已投诉</view
                >
              </view>
            </view>
          </view>
        </template>
        <view class="worder_box flex_center" v-if="!listData.length">
          <image :src="`${store.imgDomain}order_3.png`" mode="widthFix" />
          <text>暂无订单</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, reactive, watch, onBeforeMount } from 'vue';
import { useCounterStore } from '@/store';
import { onLoad, onShow } from '@dcloudio/uni-app';
import request from '@/utils/request';
import { formatTimestamp } from '@/utils/validate';
import SearchInput from '@/components/SearchInput.vue';

const searchResult = ref('');
const store = useCounterStore();
const userInfo = ref({});
const userAddressList = ref([]);
const isTrue = ref(false);
const isXq = ref(false);
const indexs = ref(0);
// 列表数据相关
const listData = ref([]);
const pageNum = ref(1);
const pageSize = ref(10);
const isNext = ref(true);
// 状态控制
const isRefreshing = ref(false); // 下拉刷新状态
const isLoading = ref(false); // 加载更多状态
const datas = ref({});
const tabList = [
  {
    text: '全部',
    user_status: '',
  },
  {
    text: '待付款',
    user_status: '2',
  },
  {
    text: '待服务',
    user_status: '3',
  },
  {
    text: '服务中',
    user_status: '4',
  },
  {
    text: '待评价',
    user_status: '8',
  },
  {
    text: '已取消',
    user_status: '1',
  },
];

const statusData = {
  1: '已取消',
  2: '待付款',
  3: '待服务',
  4: '服务中',
  5: '待评价',
  6: '售后',
  7: '退款',
};

watch(
  () => indexs.value,
  (val) => {
    pageNum.value = 1;
    pageSize.value = 10;
    getServiceOrderList(true);
  },
);
const tiemsData = ref({
  hours: 0,
  minutes: 0,
  seconds: 0,
});

const clearFun = () => {
  searchResult.value = '';
  pageNum.value = 1;
  getServiceOrderList(true);
};

// 获取我的订单列表数据

const getServiceOrderList = async (isRefresh = false, n) => {
  if (!n) {
    request('wxapp/common/getTimeStamp').then((res) => {
      times.value = res * 1000;
    });
  }

  try {
    const data = await request('wxapp/user/getServiceOrderList', {
      keywords: searchResult.value,
      user_status: tabList[indexs.value].user_status,
      currpage: pageNum.value,
      pagesize: pageSize.value,
    });
    isNext.value = data.page.isNext;
    if (isRefresh) {
      listData.value = [...data.list];
    } else {
      listData.value = [...listData.value, ...data.list];
    }
  } finally {
    isRefreshing.value = false;
    isLoading.value = false;
  }
};

// 下拉刷新处理
const handleRefresh = () => {
  // 重置状态
  pageNum.value = 1;
  isRefreshing.value = true;
  // 重新加载数据
  getServiceOrderList(true);
};

// 触底加载更多处理
const handleLoadMore = () => {
  if (!isNext.value || isLoading.value) return;
  // 加载下一页
  pageNum.value++;
  isLoading.value = true;
  getServiceOrderList();
};

const timeupFun = (row) => {
  cancelServiceOrder(row, 4, 1);
};

const handleCall = (phone) => {
  uni.makePhoneCall({
    phoneNumber: phone, // 要拨打的电话号码（字符串类型）
    success: () => {
      console.log('拨打电话请求已发出');
    },
  });
};

// 处理搜索事件
const handleSearch = (keyword) => {
  console.log('搜索关键字：', keyword);
  // 这里可以调用接口获取搜索结果等操作
  searchResult.value = keyword;
  pageNum.value = 1;
  getServiceOrderList(true);
};

// 单一取消订单服务订单
const qxFun = (row) => {
  uni.showModal({
    title: '提示',
    content: '确定要取消订单吗？',
    confirmText: '确定', // 确认按钮文字
    cancelText: '取消', // 取消按钮文字
    success: (res) => {
      if (res.confirm) {
        cancelServiceOrder(row);
      }
    },
    fail: (err) => {
      console.error('显示模态框失败', err);
    },
  });
};

// 去支付
const qzfFun = (row) => {
  uni.showModal({
    title: '提示',
    content: '确定去支付吗？',
    confirmText: '确定', // 确认按钮文字
    cancelText: '取消', // 取消按钮文字
    success: (res) => {
      if (res.confirm) {
        deleteServiceOrder(row);
      }
    },
    fail: (err) => {
      console.error('显示模态框失败', err);
    },
  });
};
// 单一删除服务订单
const deleteServiceOrder = async (row) => {
  const datas = {
    service_order_id: row.id,
  };
  await request('wxapp/user/deleteServiceOrder', datas);
  store.to(
    `/pages/server/placeAnOrder?id=${row.service_order_goods_info.goods_id}`,
  );
};

const cancelServiceOrder = async (row, cancel_type = 1, n) => {
  const datas = {
    service_order_id: row.id,
    cancel_type,
    cancel_desc: '',
  };
  await request('wxapp/user/cancelServiceOrder', datas);
  pageNum.value = 1;
  getServiceOrderList(true, n ? 1 : '');
};

const countdown = computed(() => {
  return (item) => {
    const createTimeMs = new Date(item.create_at).getTime();
    // 1. 先算总毫秒差值（关键：保留秒级精度的基础）
    let totalMsDiff = createTimeMs + nminutes.value * 60 * 1000 - times.value;
    if (totalMsDiff < 0) {
      totalMsDiff = 0;
    }
    // 2. 基于总毫秒差，依次拆解小时、分钟、秒
    const hours = Math.floor(totalMsDiff / (3600 * 1000)); // 1小时 = 3600*1000 毫秒
    const remainingMsAfterHours = totalMsDiff % (3600 * 1000); // 去掉小时后的剩余毫秒

    const minutes = Math.floor(remainingMsAfterHours / (60 * 1000)); // 1分钟 = 60*1000 毫秒
    const remainingMsAfterMinutes = remainingMsAfterHours % (60 * 1000); // 去掉分钟后的剩余毫秒

    const seconds = Math.floor(remainingMsAfterMinutes / 1000); // 剩余毫秒转秒，取整

    return {
      hours,
      minutes,
      seconds, // 最终补充秒数
    };
  };
});
const times = ref(0);
const nminutes = ref(0);

// 选中取消订单
const bindPickerChange = async (e, item) => {
  if (!e.detail?.value) return;
  const datas = {
    service_order_id: item.id,
    cancel_type: 3,
    cancel_desc: ReasonList.value[e.detail.value].cancel_service_order_reason,
  };
  await request('wxapp/user/cancelServiceOrder', datas);
  pageNum.value = 1;
  getServiceOrderList(true);
};
const ReasonList = ref([]);
// 获取所有可以选择的取消订单原因备选数据
const getRefuseReasonListForWorker = async () => {
  ReasonList.value = await request(
    'wxapp/user/getCancelServiceOrderReasonListForUser',
  );
};
// 复制文本
const copyFun = (text) => {
  // 复制文本到剪贴板
  uni.setClipboardData({
    data: text, // 要复制的文本
    success: function () {
      console.log('复制成功');
      // 可添加提示信息（如 Toast）
      uni.showToast({
        title: '复制成功',
        icon: 'none',
      });
    },
    fail: function (err) {
      uni.showToast({
        title: '复制失败',
        icon: 'none',
      });
    },
  });
};

onLoad((options) => {
  getRefuseReasonListForWorker();
  if (options.user_status) {
    if (options.user_status == 8) {
      indexs.value = 4;
    } else {
      indexs.value = options.user_status - 1;
    }
  }
});
onBeforeMount(() => {
  request('wxapp/common/getTimeStamp').then((res) => {
    times.value = res * 1000;
  });
  store
    .getParamValByKey('pending_payment_service_order_auto_cancel_minute')
    .then((res) => {
      nminutes.value = res;
    });
});
onShow(() => {
  pageNum.value = 1;
  getServiceOrderList(true);
});
</script>

<style lang="scss" scoped>
.topbars {
  background: linear-gradient(to right, #3c9fff, #3184ff);
}
.topl {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
  image {
    width: 750rpx;
    height: 364rpx;
  }
}
.page_content {
  box-sizing: border-box;
  padding: 20rpx;
  position: relative;
}
.scroll-Y {
  position: relative;
  height: 75vh;
  box-sizing: border-box;
  padding-bottom: 40rpx;
}
.tops {
  box-sizing: border-box;
  padding: 30rpx 20rpx;
  background: linear-gradient(to right, #3c9fff, #3184ff);
}

.tabs {
  width: 100%;
  display: flex;
  overflow-x: auto;
  justify-content: space-around;
  line-height: 60rpx;
  font-size: 24rpx;
  margin-bottom: 15rpx;
  view {
    position: relative;
    width: max-content;
    padding: 0 20rpx;
    flex-shrink: 0;
    &.ac {
      color: #315bc0;
      &::after {
        content: ' ';
        position: absolute;
        width: 100%;
        height: 3rpx;
        bottom: 0;
        left: 50%;
        transform: translate(-50%);
        background-color: #315bc0;
      }
    }
  }
}
.scroll-Y {
  max-height: 80vh;
}
.libox {
  border-radius: 20rpx;
  border: 1rpx solid #437ef6;
  box-sizing: border-box;
  padding: 30rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
  font-size: 24rpx;
  .libox_tops {
    display: flex;
    justify-content: space-between;
    margin-bottom: 35rpx;
    .t1 {
      color: #437ef6;
      text-decoration: underline;
    }
    .t2 {
      color: #ff7800;
    }
  }
  .li_center {
    .cen_img {
      width: 140rpx;
      height: 140rpx;
      border-radius: 10rpx;
      margin-right: 40rpx;
    }
    .cen_text_box {
      font-size: 30rpx;
      font-weight: 700;
      line-height: 40rpx;
    }
    .cen_sl {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      view {
        width: max-content;
      }
    }
  }
  .cen_je {
    font-size: 30rpx;
    color: #ff0000;
    justify-content: flex-end;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #a1cbff;
  }
  .jd_box {
    padding: 20rpx 0;
    border-bottom: 1rpx solid #a1cbff;
    &.ac {
      width: 100%;
      border: none;
      padding: 0;
    }
    .jd_text {
      position: relative;
      background-color: #3184ff;
      border-radius: 10rpx;
      color: #fff;
      line-height: 46rpx;
      padding: 0 10rpx;
      margin-right: 20rpx;
      &.ac {
        background-color: #ff5400;
        &::after {
          content: ' ';
          position: absolute;
          bottom: -16rpx;
          left: 50%;
          transform: translate(-50%);
          border-top: 10rpx solid #ff5400;
          border-right: 10rpx solid transparent;
          border-bottom: 10rpx solid transparent; /* 填充颜色 */
          border-left: 10rpx solid transparent;
        }
      }
    }
    .phone {
      margin-top: 20rpx;
      padding: 20rpx;
      border-radius: 20rpx;
      background-color: #eaf2fc;

      .head_img {
        width: 50rpx;
        height: 50rpx;
        border: 1rpx solid #047cff;
        border-radius: 50%;
        margin-right: 20rpx;
      }
      .phone_img {
        margin-left: auto;
        image {
          width: 47rpx;
          height: 46rpx;
        }
      }
    }
  }
  .bottom_time_fun {
    padding: 20rpx 0 10rpx;
    .time_icon {
      width: 28rpx;
      height: 29rpx;
      margin-right: 10rpx;
    }

    .btn {
      line-height: 44rpx;
      border-radius: 22rpx;
      border: 1rpx solid #666666;
      padding: 0 20rpx;
      margin-left: 10rpx;

      &.a1 {
        background-color: #0084f1;
        border-color: #0180f1;
        color: #fff;
      }
      &.a2 {
        background: linear-gradient(to bottom, #fe7f17, #fe4a15);
        border-color: transparent;
        color: #fff;
      }
    }
  }
}
#contactBtn {
  width: max-content;
}

.worder_box {
  flex-direction: column;
  position: absolute;
  top: 34%;
  left: 50%;
  transform: translate(-50%, -50%);
  image {
    width: 240rpx;
    margin-bottom: -20rpx;
  }
  text {
    color: $uni-text-color-grey;
  }
}
</style>
